package com.juku2024.juku.analysis.source

import android.content.Context
import android.text.TextUtils
import com.juku2024.juku.analysis.BaseHttpParse
import com.juku2024.juku.analysis.OnParseVideoListener
import com.juku2024.juku.db.entity.SourceEntity
import com.juku2024.juku.network.api.AnalysisApi
import com.juku2024.juku.network.retrofit.RetrofitUtils
import com.juku2024.juku.tools.LogC
import com.juku2024.juku.tools.VideoAnalysisUtils
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import java.net.URLDecoder

class CommonHttpParse: BaseHttpParse() {

    override fun parseVideo(context: Context, url: String, source: SourceEntity, callback: OnParseVideoListener) {
        super.parseVideo(context, url, source, callback)
        val sourceName = source.sourceName
        val targetUrl = source.url + url

//        disposable = when(source.id) {
//            1 -> parseTX(targetUrl, source, callback)
////            3 -> parseYouKu(targetUrl, source, callback)
//            else -> parseCommon(targetUrl, sourceName, callback)
//        }

        disposable = parseCommon(targetUrl, sourceName, callback)
    }

    private fun parseCommon(targetUrl: String, sourceName: String?, callback: OnParseVideoListener): Disposable {
        return RetrofitUtils.instance.getApi(AnalysisApi::class.java)
            .parse(targetUrl)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({ model ->
                if (TextUtils.isEmpty(model?.url) || model?.url?.startsWith("http", ignoreCase = true) == false || model?.code != 200) {
                    LogC.e("parse -> ${sourceName}源 -> http解析失败...")
                    callback.onFail(sourceName)
                    VideoAnalysisUtils.parseTimeAndResult(sourceName, System.currentTimeMillis() - startTime, false)
                } else {
                    callback.onSuccess(sourceName, model.url!!)
                    VideoAnalysisUtils.parseTimeAndResult(sourceName, System.currentTimeMillis() - startTime, true)
                    analysisParseDuration(sourceName)
                }
            }, {
                it?.printStackTrace()
                LogC.e("parse -> ${sourceName}源-> http解析失败...")
                callback.onFail(sourceName)
            })
    }


    private fun parseTX(url: String, source: SourceEntity, callback: OnParseVideoListener): Disposable {
        val sourceName = source.sourceName
        val startIndex = url.indexOfLast { it == '/' }
        val endIndex = url.indexOfLast { it == '.' }
        val vid = url.substring(startIndex + 1, endIndex)
        LogC.e("url -> " + url)
        LogC.e("vid -> " + vid)
        val requestUrl =
            "http://vv.video.qq.com/getinfo?charge=1&defaultfmt=auto&otype=ojson&guid=&flowid=7aa01d831abfac25c3cd88e24c0ffeb7_11001&platform=11001&sdtfrom=v5400&defnpayver=1&appVer=1.6.0&host=v.qq.com&ehost=https%3A%2F%2Fv.qq.com%2Fx%2Fcover%2Fmzc00200vkdojwu%2Fp0036386v39.html&refer=v.qq.com&sphttps=1&sphls=2&_rnd=1619512984&spwm=4&unid=3079011ce36611ea981ca0424b63310a&vid=${vid}&defn=shd&fhdswitch=&show1080p=true&dtype=1&clip=4&defnsrc=&fmt=auto&defsrc=1"
        return RetrofitUtils.instance.getApi(AnalysisApi::class.java)
            .parseQQ(requestUrl)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({ model ->
                val vi = model.vl?.vi?.firstOrNull()
                if (vi == null || TextUtils.isEmpty(vi.fn) || TextUtils.isEmpty(vi.fvkey)) {
                    parseCommon(url, sourceName, callback)
                    return@subscribe
                }
                val urlAfter = vi.fn + "?vkey=" + vi.fvkey
                disposable = RetrofitUtils.instance.getStringApi(AnalysisApi::class.java)
                    .parseString("http://42.157.129.24:3456/txym.php")
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe( subscribe2@ {
                        if (TextUtils.isEmpty(it)) {
                            parseCommon(url, sourceName, callback)
                            return@subscribe2
                        }
                        val finalUrl = it + urlAfter
                        if (TextUtils.isEmpty(it) || TextUtils.isEmpty(finalUrl)) {
                            callback.onFail(sourceName)
                        } else {
                            callback.onSuccess(sourceName, finalUrl)
                        }
                    }, {
                        it?.printStackTrace()
                        parseCommon(url, sourceName, callback)
                    })
            }, {
                it?.printStackTrace()
                parseCommon(url, sourceName, callback)
            })
    }


    private fun parseYouKu(url: String, source: SourceEntity, callback: OnParseVideoListener): Disposable? {
        disposable =  RetrofitUtils.instance.getApi(AnalysisApi::class.java)
            .getYoukuKey()
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({ youkuKey ->
                val vid = url.replace("https://v.youku.com/v_show/id_", "").replace(".html", "")
                disposable = RetrofitUtils.instance.getApi(AnalysisApi::class.java)
                    .getYoukuContent(vid, youkuKey.ccode, "192.168.1.1", youkuKey.client_ts, youkuKey.utid, youkuKey.ckey)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe( collectLabel2@ {
                        if (it == null || it.data?.stream.isNullOrEmpty()) {
                            parseCommon(url, source.sourceName, callback)
                            return@collectLabel2
                        }
                        it.data.stream.sortBy { it.height }
                        if (TextUtils.isEmpty(it.data.stream.last()?.m3u8_url)) {
                            parseCommon(url, source.sourceName, callback)
                            return@collectLabel2
                        }

                        val headerMap = HashMap<String, String>()
                        if (!TextUtils.isEmpty(youkuKey.cookie)) {
                            headerMap["Cookie"] = URLDecoder.decode(youkuKey.cookie, "utf-8")
                            headerMap["Referer"] = "http://video.tudou.com/"
                            headerMap["User-Agent"] = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36"
                        }
                        callback.onSuccess("本地解析", it.data.stream.last().m3u8_url, headerMap)
                    }, {
                        it.printStackTrace()
                        parseCommon(url, source.sourceName, callback)
                    })

            }, {
                it.printStackTrace()
                parseCommon(url, source.sourceName, callback)
            })
        return disposable
    }

}